<template>
  <div class="table-operations">
    <a-space>
      <a-upload accept=".xlsx,.xls" :before-upload="beforeUpload" :show-upload-list="false">
        <a-button type="primary" :loading="importLoading">
          <UploadOutlined />导入数据
        </a-button>
      </a-upload>
      <a-button @click="handleExport"><DownloadOutlined />导出数据</a-button>
    </a-space>
    <a-table :data-source="tableData" :columns="columns" :pagination="tablePageConfig" size="small"/>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { exportExcel, handleExcelImport, validateData } from '@/plugin/useExcel';
import {tablePageConfig} from "@/config";

interface TableItem {
  name: string;
  category:string,
  cost_price:number|undefined,
  price:number|undefined,
  unit:string
}
const columns: TableColumnsType = [
  { key: 'name', title: '产品名称', dataIndex: 'name' },
  { key: 'category', title: '分类', dataIndex: 'category' },
  { key: 'cost', title: '进货价',dataIndex: 'cost' },
  { key: 'price', title: '销售价',dataIndex: 'price' },
  { key: 'unit', title: '单位',dataIndex: 'unit'}
]
const importLoading = ref(false);
const tableHeaders = ['名称', '分类', '进货价', '销售价', '单位'];
const tableData = ref<TableItem[]>()
// 导出处理
const handleExport = () => {
  const exportData = [
    tableHeaders, // 表头
    ...tableData.value.map(item => [item.name, item.category, item.cost_price, item.price, item.unit])
  ];
  //生成文件名：唱片报价-日期
  const date = new Date().toISOString().slice(0, 10);
  exportExcel(exportData, `产品报价-${date}.xlsx`);
  message.success('导出成功');
};

// 导入处理
const beforeUpload = (file: File) => {
  importLoading.value = true;
  handleExcelImport(file, (importData) => {
    try {
      const [headers, ...rows] = importData;
      if (!validateData(headers)) {
        message.error('文件格式不符合要求');
        return;
      } else if (rows.length === 0) {
        message.error('文件为空');
        return;
      }
      tableData.value = rows.map((row) => ({
        name: String(row[0]),
        category: String(row[1]),
        cost_price: Number(row[2])|0,
        price: Number(row[3])|0,
        unit: String(row[4])
      }));
      message.success(`成功导入${rows.length}条数据`);
    } catch (error) {
      message.error('数据解析失败'+error);
    } finally {
      importLoading.value = false;
    }
  });

  return false; // 阻止默认上传
};

// 数据校验方法
const validateImportData = (headers: any[]) => {
  return (
      headers.length === tableHeaders.length &&
      headers.every((h, i) => h === tableHeaders[i])
  );
};
</script>

<style scoped>
.table-operations {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  width: 700px;
}
</style>
